<?php
/**
 * Created by PhpStorm.
 * User: vanity
 * Date: 2018/1/4
 * Time: 10:48
 */
namespace Admin\Model;
class ImageUploadModel
{
    protected  $file;
    public function uploadAvatar($file)
    {
        $this->file = $file['image'];
        $allowedExtensions = ["png", "jpg", "jpeg", "gif"];

        $check = $this->check($allowedExtensions);

        if (!$check['status']) {
            return $check;
        }
        $destPath = '/Public/uploads/avatar';

        return $this->file.'|'.PATHINFO_EXTENSION.'|'.pathinfo($this->file, PATHINFO_EXTENSION);
        $newFileName = md5(time().rand(0,10000)).'.'.pathinfo($this->file, PATHINFO_EXTENSION);
        return $newFileName;
        if(!move($destPath, $newFileName)){
            return ['status' => '系统异常，文件保存失败'];
        }
        return ['status' => true, 'fileName' => $newFileName];
    }
    private function check($allowedExtensions)
    {
        if($this->file['error'] != 0){
            return ['status' => false,'msg'=>'文件异常'];
        }
        if($this->file['type'])
        if (!$this->checkAllowedExtensions($allowedExtensions)) {
            return ['status' => false, 'msg' => '非法的图片格式'];
        }
        if (filesize($this->file['image']['size']) > 2 * 1024 * 1024) {
            return ['status' => false, 'msg' => '图片大小不能大于2M'];
        }
        return ['status' => true];
    }
    /**
     * 检测上传文件是否合法
     *
     * @param $allowedExtensions
     * @return bool
     */
    private function checkAllowedExtensions($allowedExtensions)
    {
        // 如果是图像文件 检测文件格式
        if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf'))) {
            $info = getimagesize($file['tmp_name']);
            if(false === $info || ('gif' == strtolower($file['extension']) && empty($info['bits']))){
                $this->error = '非法图像文件';
                return false;
            }
        }
        return true;
    }
    function getsize($size, $format = 'kb') {
        $p = 0;
        if ($format == 'kb') {
            $p = 1;
        } elseif ($format == 'mb') {
            $p = 2;
        } elseif ($format == 'gb') {
            $p = 3;
        }
        $size /= pow(1024, $p);
        return number_format($size, 3);
    }
}